{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ce5e76a5-222b-408d-b90c-19a801432e66",
   "metadata": {},
   "source": [
    "# LangChain 核心模块 Agent - ReAct\n",
    "\n",
    "ReAct 核心思想是 推理+操作，本示例以` Google Search` 和 `LLM Math` 作为可选操作集合（toolkits），实现 ReAct 功能。\n",
    "\n",
    "以下`SERPAPI_API_KEY`仅为示例，请访问 https://serpapi.com 注册账号并替换为自己的 `API_KEY`（每月100次免费调用）\n",
    "\n",
    "```python\n",
    "import os\n",
    "\n",
    "# 更换为自己的 Serp API KEY\n",
    "os.environ[\"SERPAPI_API_KEY\"] = \"xxx\"\n",
    "```\n",
    "\n",
    "建议将其设置为环境变量，而不是在代码中显式明文设置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "108d8a86-02a9-4618-b6a0-dc115c4ad532",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install -U langchain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d03a5086-d453-44f2-898b-0fecb746d0c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import OpenAI\n",
    "\n",
    "llm = OpenAI(model_name=\"gpt-3.5-turbo-instruct\", temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9e7e7202-625a-4cec-999a-321a40115792",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import load_tools\n",
    "from langchain.agents import initialize_agent\n",
    "from langchain.agents import AgentType\n",
    "\n",
    "#加载 LangChain 内置的 Tools\n",
    "tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d89d569f-5313-42f3-8f1a-ea45fb1ea035",
   "metadata": {},
   "source": [
    "### 使用语言模型（gpt-3.5-turbo-instruct）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "70af3538-18c4-4c64-99a7-96b32038d31b",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_1745838/3898936477.py:2: LangChainDeprecationWarning: The function `initialize_agent` was deprecated in LangChain 0.1.0 and will be removed in 1.0. Use Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. instead.\n",
      "  agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n"
     ]
    }
   ],
   "source": [
    "# 实例化 ZERO_SHOT_REACT Agent\n",
    "agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "484bba88-885b-4630-a9a9-b2ff6241df83",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m I should use the search engine to find information about Leonardo DiCaprio's girlfriend.\n",
      "Action: Search\n",
      "Action Input: \"Leonardo DiCaprio girlfriend\"\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3mVittoria Ceretti\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m Now I need to use the calculator to calculate 0.43 times the age of Vittoria Ceretti.\n",
      "Action: Calculator\n",
      "Action Input: 0.43 * 23\u001b[0m\n",
      "Observation: \u001b[33;1m\u001b[1;3mAnswer: 9.89\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
      "Final Answer: 9.89\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?', 'output': '9.89'}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent.invoke(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b816038d-6f3a-47cb-b614-e432db8c1883",
   "metadata": {},
   "source": [
    "### 使用聊天模型（gpt-4o-mini）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "448c877f-577b-4277-a155-51223dc3d949",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: 我需要先查找莱昂纳多·迪卡普里奥目前的女朋友是谁，然后再计算她年龄的0.43次方。首先，我将搜索他的女朋友的最新信息。\n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Search\",\n",
      "  \"action_input\": \"莱昂纳多·迪卡普里奥 现任女朋友\"\n",
      "}\n",
      "```\n",
      "\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m['刚和25岁超模女友卡米拉分手的小李子莱昂纳多·迪卡普里奥，被曝22岁新女友“火速上线”。 这位被换女友如换衣服的小李子“临幸”的妙龄女子就是乌克兰超模玛莉 ...', '比莱昂纳多·迪卡普里奥的现任女友还大3岁。” 小李子曾与年轻模特交往过，比如吉赛尔·邦辰、芭尔·拉法利和卡米拉·莫罗内。 他最近还和吉吉·哈迪德传出 ...', '2022年12月至今，这是莱昂纳多的公开约会对象。 维多利亚·拉马斯是一位以色列超模，也是知名演员洛伦佐·拉马斯的女儿。 拉马斯出生于1999年，今年24岁， ...', '49岁的莱昂纳多·迪卡普里奥，这位被粉丝亲切称为“小李子”的好莱坞巨星，近日和26岁的女友Vittoria Ceretti（维多利亚·切蕾蒂）在洛杉矶被拍到牵手逛街， ...', '49岁的莱昂纳多·迪卡普里奥和25岁女友Vittoria Ceretti及其女友的家人现身伦敦。ps：大胆的预测一下，小李子不会要结婚了吧？ \\u200b', '23年交了57个女朋友,颜值高就是任性! 源史斋. 9万次播放. 2019年,小李子莱昂纳多和21岁的模特女友在泰国海边度假时的 ... 迪卡普里奥莱昂纳多24岁新女友. 没有更多了.', '卡米拉·莫罗尼是莱昂纳多的现任女友，她不仅是一位阿根廷超模，还拥有显赫的家庭背景。 自2017年以来，两人的恋情一直稳定发展，卡米拉也即将年满25岁， ...', '“BREAKING：莱昂纳多·迪卡普里奥的前女友，卡米拉·莫罗内Camila Morrone ... 只有现任女友卡米拉·莫罗内，从2017年底至今快5年，两人玩得可嗨了 ...', '比如莱昂纳多·迪卡普里奥的女朋友们。 莱昂纳多只跟25岁以下的女性交往人尽皆知，而现女友卡米拉即将于6月年满25周岁。全世界的吃瓜网友都在掰着手指 ...', '小李子携新女友度假⛱️。小李子莱昂纳多·迪卡普里奥携新女友在意大利度假。话说超模的身材好扁平啊，可能更适合T台和硬照吧#小李子 #超模.']\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m我需要确认莱昂纳多·迪卡普里奥的现任女朋友的年龄，然后计算她年龄的0.43次方。根据搜索结果，维多利亚·拉马斯（Vittoria Ceretti）是他的现任女友，24岁。接下来，我将计算24的0.43次方。\n",
      "\n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Calculator\",\n",
      "  \"action_input\": \"24^0.43\"\n",
      "}\n",
      "```\n",
      "\u001b[0m\n",
      "Observation: \u001b[33;1m\u001b[1;3mAnswer: 3.9218486893172186\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m我现在知道维多利亚·拉马斯（Vittoria Ceretti）是莱昂纳多·迪卡普里奥的现任女朋友，她24岁。经过计算，她年龄的0.43次方约为3.92。\n",
      "\n",
      "Final Answer: 3.92\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?', 'output': '3.92'}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\", temperature=0)\n",
    "agent = initialize_agent(tools, chat_model, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
    "agent.invoke(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67f4728e-bf1f-4643-a2ee-8f8679ddc58a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
